package com.springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.springcloud.pojo.Address;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

/**
 * @Author 咕唧
 * @Date 2022/6/25 15:42
 * @Version 1.0
 */
@RestController
@RequestMapping("/address")
@RefreshScope //代表知道配置发生变化的时候会重新加载配置
public class AddressController {
    @Value("${server.port}")
    private int port;

    @Value("${women.user.name}")
    private String name;

    @GetMapping("/name")
    public String getName() {
        return name;
    }

    @GetMapping("/info/{id}")
    public Address findById(@PathVariable Long id) {
        Address address = new Address();
        address.setId(id);
        address.setAddressName("沙阳路一通小区-->" + id + "-->" + port);
        address.setPhoneNum("14874874874==>" + id + "-->" + port);
        return address;

    }

    @GetMapping("/test/{id}")
    //给当前方式设置降级方法，当改方法出现问题时，会自动调用该方法的降级方法
    //降级方法的参数名字要和HystrixCommand注解指定的一致，参数需要保持相同
    @HystrixCommand(fallbackMethod = "testHystrix")
    public Address test(@PathVariable Long id) {
        //Thread.sleep(3000);
        if (new Random().nextBoolean()) {
            int i = 1 / 0;
        }
        Address address = new Address();
        address.setId(id);
        address.setAddressName("这是测试的数据-->" + id + "-->" + port);
        address.setPhoneNum("测试手机号147==>" + id + "-->" + port);
        return address;
    }

    @GetMapping("/test2")
    @HystrixCommand(fallbackMethod = "test2Hystrix")
    public String test2(String name) {
        if (new Random().nextBoolean()) {
            int i = 1 / 0;
        }
        return "test2====>" + name;
    }

    @GetMapping("/test3")
    public String test3(String name, int age) {
        return "test3====>" + name + "====>age---->" + age;
    }

    @PostMapping("/test4")
    public Address test4(@RequestBody Address address) {
        address.setAddressName("这是test4设置的地址");
        return address;
    }

    /**
     * 这个是test方法指定的托底数据
     *
     * @param id
     * @return
     */
    public Address testHystrix(Long id) {

        Address address = new Address();
        address.setId(id);
        address.setAddressName("这是测试的托底数据");
        return address;
    }

    public String test2Hystrix(String name) {

        return "这是test2222方法返回的降级数据";
    }


}
